package interval;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/*
 *@description 插入区间
 *@author hkfan
 *@version 1.0
 *@create 2025/6/5 16:10
 */
public class LeetCode_57 {

    public int[][] insert(int[][] intervals, int[] newInterval) {
        //1. 定义
        int[][] nums=new int[intervals.length+1][2];
        for (int i = 0; i < intervals.length; i++) {
            nums[i]=intervals[i];
        }
        nums[intervals.length]=newInterval;
        ArrayList<int[]> list = new ArrayList<>();
        //2. 排序
        Arrays.sort(nums, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });
        //3. 循环处理
        for (int i = 0; i < nums.length; ) {
            int[] temp = nums[i];
            int j = temp[1];
            while (i+1<nums.length && j>=nums[i+1][0]){
                i++;j=Math.max(j,nums[i+1][1]);
            }
            temp[1]=j;i++;
            list.add(temp);
        }
        //4. 处理结果
        int[][] res = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            res[i]=list.get(i);
        }
        return res;


    }
}
